package org.shoukaiseki.aqoeous.config.dbconfig;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.shoukaiseki.aqoeous.config.dbconfig.annotation.VirtualDBDatasource;
import org.shoukaiseki.aqoeous.constants.LoggerConstants;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.inject.Named;
import javax.sql.DataSource;

/**
 * 虚拟数据源,该数据源无效<br>
 *     因为必须得有一个数据源有 @Primary 注解指定为主要的数据源,所以默认引入该数据源作为主要,实际未指定数据源情况下是会报错的
 *   <br>
 * org.shoukaiseki.aqoeous.config.dbconfig.VirtualDBDataSourceConfig
 * <br>
 *
 * @author 蒋カイセキ    Japan-Tokyo  19-2-11 下午2:39<br>
 * ブログ http://www.shoukaiseki.top/<br>
 * E-メール jiang28555@Gmail.com<br>
 **/
@Configuration
@MapperScan(annotationClass = VirtualDBDatasource.class,basePackages = DataBaseConfigConstants.PACKET_PREFIX,sqlSessionFactoryRef = DataBaseConfigConstants.VIRTUALDB_SQLSESSION_FACTORY)
public class VirtualDBDataSourceConfig  {

    final static Logger logger=DataBaseConfigConstants.logger;

    @Value(DataBaseConfigConstants.MAPPER_LOCATION)
    String mapperLocation;

    public VirtualDBDataSourceConfig(){
    }


    @Primary
    @Bean(name = DataBaseConfigConstants.VIRTUALDB_DATASOURCE, destroyMethod = "")
    @ConfigurationProperties(prefix = "sks.multiple.datasource.virtualdb")
    public DataSource dataSource() {
        // 属性由springboot自动填写
        return new DruidDataSource();
    }


    @Primary
    @Bean(DataBaseConfigConstants.VIRTUALDB_SQLSESSION_FACTORY)
    public SqlSessionFactory sqlSessionFactory(@Named(DataBaseConfigConstants.VIRTUALDB_DATASOURCE) final DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocation));

        logger.debug("{}{}", LoggerConstants.PREFIX,"VirtualDBDataSourceConfig.sqlSessionFactory");
        logger.debug("{}{}.url={}",LoggerConstants.PREFIX,"VirtualDBDataSourceConfig",((DruidDataSource)dataSource).getUrl());

        return bean.getObject();
    }

    @Primary
    @Bean(name = DataBaseConfigConstants.VIRTUALDB_TRANSACTIONMANAGER)
    public DataSourceTransactionManager transactionManager(@Named(DataBaseConfigConstants.VIRTUALDB_DATASOURCE) final DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

